import 'dart:io';

import 'package:inmotion_pro/config/const.dart';
import 'package:inmotion_pro/extension/future_error_handler.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_account.dart';
import 'package:inmotion_pro/l10n/local.dart';
import 'package:inmotion_pro/pages/mine/user_info/mixin.dart';
import 'package:inmotion_pro/pages/mixin/cache_mixin.dart';
import 'package:inmotion_pro/service/global_service.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import '../../../utils/aliyun_oss_util.dart';
import '../../mixin/vehicle_type_mixin.dart';
import '../../models/settting_item_model.dart';
import 'state.dart';

// 用户信息控制器
class UserInfoController extends GetxController
    with UserBasicInformationMixin, CacheMixin {
  // 状态
  UserInfoState state = UserInfoState();

  // 车辆类型
  final VehicleType _vehicleType = GlobalService.to.currentVehicleType;

  @override
  void onInit() {
    super.onInit();
    _reloadData();
  }

  // 重新加载数据
  _reloadData() {
    // 初始化功能列表
    state.itemList.value = _vehicleType.userInfoCellList();
    // 赋值用户信息
    state.userInfo.value = GlobalService.to.cacheUserInfo.value;
    // 赋值OnTap事件
    for (int i = 0; i < state.itemList.length; i++) {
      for (int j = 0; j < state.itemList[i].subItems.length; j++) {
        _setCellOnTap(state.itemList[i].subItems[j]);
      }
    }
  }

  // 设置页面cell点击事件
  _setCellOnTap(SettingRowModel model) async {
    if (model.title == local.account) {
      // 账号
      model.value = state.userInfo.value.email;
    } else if (model.title == local.nick_name) {
      // 昵称
      model.value = state.userInfo.value.nickname;
      model.onTap = () {
        LxAlert.show(local.nick_name,
            cancelTitle: local.cancel,
            confirmTitle: local.confirm,
            textFieldValue: model.value,
            textFieldPlaceholder: local.enter_nickname,
            confirmCallback: (text) async {
          Loading.showLoading(null);
          _updateUserInfo(nickname: text);
        });
      };
    } else if (model.title == local.signature) {
      // 签名
      model.value = state.userInfo.value.signature.isEmpty
          ? local.enter_signature
          : state.userInfo.value.signature;
      model.onTap = () {
        // 签名
        LxAlert.show(local.signature,
            cancelTitle: local.cancel,
            confirmTitle: local.confirm,
            textFieldValue:
                model.value == local.enter_signature ? "" : model.value,
            textFieldPlaceholder: local.enter_signature,
            confirmCallback: (text) async {
          Loading.showLoading(null);
          _updateUserInfo(signature: text);
        });
      };
    }
    state.itemList.refresh();
  }

  // 更新用户信息
  _updateUserInfo({
    String? avatar,
    String? nickname,
    String? signature,
  }) {
    ApiHelper()
        .updateUserInfo(
            avatar: avatar, nickname: nickname, signature: signature)
        .then((success) async {
      if (success) {
        Loading.showSuccess(local.setting_successful);
        if (nickname != null) {
          state.userInfo.value.nickname = nickname;
          await cacheMixinUpdateUser(
            state.userInfo.value.uid,
            nickName: nickname,
          );
        }
        if (signature != null) {
          state.userInfo.value.signature = signature;
          await cacheMixinUpdateUser(
            state.userInfo.value.uid,
            signature: signature,
          );
        }
        await _refreshUserInfo();
        _reloadData();
      } else {
        Loading.showToast(local.fail);
      }
    }).catchErrorHandler();
  }

  // 刷新用户信息
  Future<bool> _refreshUserInfo() {
    return ApiHelper().getUserInfo().then((model) async {
      state.userInfo.value = model;
      return cacheMixinUpdateUser(
        model.uid,
        avatar: model.avatar,
        nickName: model.nickname,
        signature: model.signature,
        phone: model.phone,
        email: model.email,
      );
    });
  }

  // 点击头像
  clickAvatarOnTap() {
    mixinClickAvatar(callback: (filePath) {
      debugPrint("点击头像: $filePath");
      Loading.showLoading(local.uploading);
      AliyunOSSUtil()
          .uploadFile(FileDirectory.avatar, File(filePath))
          .then((fileName) {
        if (fileName != null) {
          _updateUserInfo(avatar: "$ossFileUrl$fileName");
        } else {
          Loading.showToast(local.upload_failed);
        }
      }).catchErrorHandler();
    });
  }
}
